//
//  ContentView.swift
//  XCBlue
//
//  Created by mac on 2025/2/13.
//

import SwiftUI


struct ContentView: View {
    @StateObject private var bluetoothManager = XCBluetoothManager.shared
    
    var body: some View {
        NavigationView {
            VStack {
                if bluetoothManager.discoveredPeripherals.isEmpty {
                    if bluetoothManager.isScanning {
                        Text("正在扫描...")
                    } else {
                        Text("未发现设备")
                    }
                }
                
                List(bluetoothManager.discoveredPeripherals) { model in
                    Button(action: {
                        // 执行连接操作
                        if let peripheral = model.peripheral {
                            bluetoothManager.centralManager.connect(peripheral, options: nil)
                        }
                    }) {
                        HStack {
                            Text(model.peripheral?.name ?? "未知设备")
                                .font(.system(size: 12))
                            Text(model.macAddress ?? "未知地址")
                                .font(.system(size: 12))
                            Text(model.isCanConect ? "可连接" : "已被连接")
                                .font(.system(size: 10))
                        }
                        .background(model.isConnected ? Color.red : Color.white)
                        .padding()
                    }
                }
                
                
                // TextField 和发送按钮
                TextField("发送消息", text: .constant(""))
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                    .padding()
                
                HStack {
                    Button("发送") {
                        // bluetoothManager.sendMessage("Hello, Bluetooth!")
                        XCBlueSendTool.sendTimeToDevice()
                    }
                    .padding(.horizontal,10)
                    .background(Color.orange)
                    
                    Button("获取电量") {
                        XCBlueSendTool.getDeviceElectricity()
                    }
                    .padding(.horizontal,10)
                    .background(Color.green)
                }
            }
            .navigationTitle("蓝牙设备")
            .onAppear {
                bluetoothManager.startScanning()
            }
        }
    }
}


#Preview {
    ContentView()
}
